package com.jpa.eclipselink.demo;

import com.alibaba.fastjson.JSON;
import com.jpa.eclipselink.demo.entity.Todo;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import java.util.List;

/**
 * package com.jpa.eclipselink.demo
 * description:
 *
 * 参考：https://www.vogella.com/tutorials/JavaPersistenceAPI/article.html#installation_database
 * https://www.vogella.com/tutorials/JavaPersistenceAPI/article.html
 *
 * @author tree
 * @date 2019-05-29 09:29
 */
public class App {

    private static final String PERSISTENCE_UNIT_NAME = "todos";
    private static EntityManagerFactory factory;

    public static void main(String[] args) {
        factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
        EntityManager em = factory.createEntityManager();
        // read the existing entries and write to console
        Query q = em.createNativeQuery("select * from todo ");//createQuery("select t from Todo t");
        List<Object> todoList = q.getResultList();
        for (Object todo : todoList) {
            System.out.println(JSON.toJSONString(todo));
        }
        System.out.println("Size: " + todoList.size());

        // create new todo
        em.getTransaction().begin();
        Todo todo = new Todo();
        todo.setSummary("This is a test");
        todo.setDescription("This is a test");
        em.persist(todo);
        em.getTransaction().commit();

        em.close();
    }
}
